package com.moli.iov.third.invocation.op.base;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.moli.iov.cache.RedisUtil;
import com.moli.iov.exception.BusinessException;
import com.moli.iov.third.config.OpProperties;
import com.moli.iov.third.contstants.Constants;
import com.moli.iov.util.HttpUtil;
import com.moli.iov.util.StringUtil;
import java.io.IOException;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * <p>
 *
 * </p>
 *
 * @author zql
 * @since 2019/10/9 15:29
 */
@Slf4j
@Component
public class TokenHandler {

  @Autowired
  private RedisUtil redisUtil;

  @Autowired
  private OpProperties opProperties;

  /**
   * 获取凭证token
   * @return
   * @throws Exception
   */
  public String getToken() throws IOException {

    String token = redisUtil.get(Constants.TASK_SERVICE_OP_TOKEN);

    if (StringUtil.isBlank(token)) {
      return getTokenReal();
    }

    return token;
  }


  /**
   * 实际获取token的方法
   * @return
   */
  protected String getTokenReal() throws IOException {
    Map<String, String> params = Maps.newHashMap();
    params.put("account", opProperties.getAccount());
    params.put("password", opProperties.getPassword());

    String result = HttpUtil.postJson(opProperties.getLoginUrl(), JSONObject.toJSONString(params), Maps.newHashMap());
    if(StringUtil.isBlank(result)){
      throw new BusinessException("获取token失败，返回result空");
    }

    JSONObject resultObj = JSONObject.parseObject(result);

    if(Constants.OP_SUCCESS != resultObj.getInteger("code")){
      log.error("登陆失败，OP返回状态非{}  入参：{}, 出参：{}", Constants.OP_SUCCESS, params, resultObj);
      throw new BusinessException(resultObj.getString("message"));
    }
    JSONObject data = resultObj.getJSONObject("data");
    if(data == null){
      log.error("登陆失败，返回data为空  入参：{}, 出参：{}", params, resultObj);
      throw new BusinessException("登陆失败，返回data为空");
    }

    String token = data.getString("token");
    if(StringUtil.isBlank(token)){
      log.error("登陆失败，返回token为空  入参：{}, 出参：{}", params, resultObj);
      throw new BusinessException("登陆失败，返回token为空");
    }
    redisUtil.set(Constants.TASK_SERVICE_OP_TOKEN, token, Constants.OP_TOKEN_TIME);
    return token;
  }

}
